/**
 * Created by 15c on 2017/11/2.
 */

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateUtil {
    private static StandardServiceRegistry registry;
    private static SessionFactory sessionFactory;

    static {
        if (sessionFactory == null) {
            registry = new StandardServiceRegistryBuilder().configure().build();
            MetadataSources metadataSource = new MetadataSources(registry);
            try {
                sessionFactory = metadataSource.buildMetadata().buildSessionFactory();
            } catch (Exception exception) {
                exception.printStackTrace();
                StandardServiceRegistryBuilder.destroy(registry);
            }
        }
    }

    public static Session openSession() {
        return sessionFactory.openSession();
    }

    public static void closeSession(Session session) {
        try {
            if (session != null) {
                sessionFactory.close();
            }
        } catch (HibernateException e) {
            e.printStackTrace();
        }
    }
}

